#!/usr/bin/env python


__author__= 'yingnn'

'''methylation fitting using random forest'''


import sys


if len(sys.argv) < 3:
	print sys.argv[0], "fname n_trees n_jobs\n200 trees recommended as a start.\n"
	exit()

fname=sys.argv[1]
n_trees=int(sys.argv[2])
# n_trees=sys.argv[2]
jobs=int(sys.argv[3])

# these modules should have been installed. Or u maybe try setting environment variable "export PYTHONPATH=$PYTHONPATH:/mnt/ilustre/app/medical/tools/py_module"
import pandas as pd
import numpy as np
import random
from sklearn.ensemble import RandomForestClassifier as rfc

dat= pd.read_table(fname, header=None) 

dat= dat.transpose()

dat1= dat.dropna(axis=1, how='any') # drop columns if there is a not-available value in them. 



n_sample= dat1.shape[0]
n_sampling=n_sample/10

idx_sample_bool= np.repeat(True, n_sample)

idx_sample= np.arange(1, n_sample) # no first row, it is feature id.




idx_valid= random.sample(idx_sample, n_sampling)

sample_valid= dat1.loc[idx_valid]

idx_valid.append(0) # no first row in training set
idx_sample= np.hstack(([0], idx_sample))

idx_sample_bool[idx_valid]=False
sample_train= dat1.loc[idx_sample[idx_sample_bool]]


	
rfc1= rfc(n_estimators=n_trees, oob_score=True, n_jobs=jobs, verbose=10)

# rfc1.fit(dat1.iloc[1:, 1:], dat1.iloc[1:, 0]) # [x,y], x is like [n_samples, n_features], y is like [n_samples, ]

rfc1.fit(sample_train.iloc[:, 1:], sample_train.iloc[:, 0])

#pred= rfc1.predict(x_new)
# proba= rfc1.predict_proba(x_new)
sc= rfc1.score(sample_valid.iloc[:, 1:], sample_valid.iloc[:, 0])
# rfc1.classes_ # list of classes
# rfc1.n_classes_ # number of classes
# rfc1.n_features_
# rfc1.feature_importances_



f= open('score1w.txt', 'a')
f.write("\t".join([str(rfc1.oob_score_), str(sc), fname])+ "\n")
f.close()



